//
//  XDMailSendViewController.m
//  iphone.mobileoa
//
//  Created by 李亚春 on 13-6-5.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "XDMailSendViewController.h"
#import "XDPersonChooseViewController.h"
#import "MailSendTask.h"
#import "UIViewController+MJPopupViewController.h"
#import "XDAttachChooseViewController.h"
#import "XDMailSendAttachListCell.h"
#import "ATTACHList.h"
#import <QuartzCore/QuartzCore.h>


#define SJR_STORE_FlAG @"SJR_STORE_FlAG"
#define CSR_STORE_FlAG @"CSR_STORE_FlAG"

@interface XDMailSendViewController ()
{
    int pushflag;
    NSMutableString *sjrguids,*csrguids;
    NSString *sendMailTaskGuid;
    NSMutableArray *attachArray;
    NSString *enterFlag;
}
@end

@implementation XDMailSendViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        sjrguids = [[NSMutableString alloc]initWithString:@""];
        csrguids = [[NSMutableString alloc]initWithString:@""];
    }
    return self;
}
- (IBAction)addAttachAction:(id)sender {
    XDAttachChooseViewController *vc = [[XDAttachChooseViewController alloc]init];
    vc.delegate = self;
    [self presentPopupViewController:vc animationType:MJPopupViewAnimationFade];
}

-(id)initWithParams:(NSMutableDictionary *)params
{
    [super initWithParams:params];
    pushflag = 0;
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud removeObjectForKey:SJR_STORE_FlAG];
    [ud removeObjectForKey:CSR_STORE_FlAG];
    
    NSString *names = [intentParams objectForKey:@"names"];
    NSString *guids = [intentParams objectForKey:@"guids"];
    
    if (names!=nil&&guids!=nil) {
        pushflag = 1;
        
        NSArray *namearr = [names componentsSeparatedByString:@";"];
        NSArray *guidarr = [guids componentsSeparatedByString:@";"];
        
        NSMutableArray *passedPerson = [[NSMutableArray alloc]init];
        for (int i=0; i<namearr.count-1; i++) {
            NSMutableDictionary *sp = [[NSMutableDictionary alloc]init];
            [sp setObject:[namearr objectAtIndex:i] forKey:@"displayname"];
            [sp setObject:[guidarr objectAtIndex:i] forKey:@"userguid"];
            [passedPerson addObject:sp];
            [sp release];
        }
        
        [ud setObject:passedPerson forKey:SJR_STORE_FlAG];
        [passedPerson release];
    }
    
    return self;
}

-(id)init
{
    [self init];
    pushflag = 0;
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud removeObjectForKey:SJR_STORE_FlAG];
    [ud removeObjectForKey:CSR_STORE_FlAG];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"写邮件";
    [self.sv setContentSize:CGSizeMake(320, 520)];
    
    attachArray = [[NSMutableArray alloc]init];
    
    UIButton* backButton= [[UIButton alloc] initWithFrame:CGRectMake(0,0,40,20)];
    [backButton setBackgroundImage:[UIImage imageNamed:@"top_share"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(sendMail) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.rightBarButtonItem = leftBarButtonItem;
    [leftBarButtonItem release];
    [backButton release];
    
    enterFlag = [intentParams objectForKey:@"EnterFlag"];
    if ([enterFlag isEqualToString:@"2"]) {
        self.title = @"邮件回复";
        self.lbMailTitle.text = [NSString stringWithFormat:@"回复:%@",[intentParams objectForKey:@"MailTitle"]];
        sjrguids = [intentParams objectForKey:@"ToUserGuidList"];
        self.lbsjr.text = [intentParams objectForKey:@"ToUserDispNameList"];
    }
    else if([enterFlag isEqualToString:@"3"])
    {
        self.title = @"邮件转发";
        self.lbMailTitle.text = [NSString stringWithFormat:@"转发:%@",[intentParams objectForKey:@"MailTitle"]];
        NSMutableArray *zfAttachList = [intentParams objectForKey:@"zfAttachList"];
        for (int i=0; i<zfAttachList.count; i++) {
            ATTACHList *m = [zfAttachList objectAtIndex:i];
            NSMutableDictionary *fdic = [[NSMutableDictionary alloc]init];
            [fdic setObject:m.ATTACHFILENAME forKey:@"filename"];
            [fdic setObject:m.AttachGuid forKey:@"fileguid"];
            [fdic setObject:@"" forKey:@"filepath"];
            [fdic setObject:@"2" forKey:@"type"];
            [attachArray addObject:fdic];
        }
    }
}

-(void)sendMail
{
    if (self.lbsjr.text.length==0) {
        [UITool toast:@"请选择收件人！"];
        return;
    }

    if (self.lbMailTitle.text.length==0) {
        [UITool toast:@"请输入邮件标题！"];
        return;
    }
    
    NSString *IFNotice = @"0";
    if (cbMsg.isOn) {
        IFNotice = @"1";
    }
    
    NSMutableDictionary *params = self.getPassDictionary;
    [params setObject:IFNotice forKey:@"IFNotice"];
    [params setObject:self.lbMailTitle.text forKey:@"Subject"];
    [params setObject:sjrguids forKey:@"ToUserGuidList"];
    [params setObject:@"" forKey:@"SecretUserGuidList"];
    [params setObject:csrguids forKey:@"ChaoSongUserGuidList"];
    [params setObject:self.tvContent.text forKey:@"MailContent"];
    [params setObject:attachArray forKey:@"ATTACHList"];
    if ([enterFlag isEqualToString:@"2"]||[enterFlag isEqualToString:@"3"]) {
        NSString *FROMDISPNAME = [intentParams objectForKey:@"FROMDISPNAME"];
        NSString *SENDTIME = [intentParams objectForKey:@"SENDTIME"];
        NSString *MailTitle = [intentParams objectForKey:@"MailTitle"];
        
        NSString *mailsendinfo = [NSString stringWithFormat:@"<b>发件人：</b>%@<br/><br/><b>发件时间：</b>%@<br/><br/><b>主题：</b>%@<br/><br/>",FROMDISPNAME,SENDTIME,MailTitle];
        NSString *lastC = [NSString stringWithFormat:@"%@<br/><br/><hr/><br/><br/>%@%@",self.tvContent.text,mailsendinfo,[intentParams objectForKey:@"MailContent"]];
        [params setObject:lastC forKey:@"MailContent"];
        
    }
    [self showMBPHUDWithMessage:@"正在发送邮件..."];
    sendMailTaskGuid = [[[MailSendTask alloc]initWithContext:self andParams:params]startTask];
}
- (IBAction)sjrAddPerson:(id)sender {
    pushflag = 1;
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    
    if ([ud objectForKey:SJR_STORE_FlAG]!=nil) {
        [params setObject:[ud objectForKey:SJR_STORE_FlAG] forKey:@"withPerson"];
    }
    
    [params setObject:SJR_STORE_FlAG forKey:@"whichControl"];
    XDPersonChooseViewController *vc = [[XDPersonChooseViewController alloc]initWithParams:params];
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)csrAddPerson:(id)sender {
    pushflag = 2;
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    
    if ([ud objectForKey:CSR_STORE_FlAG]!=nil) {
        [params setObject:[ud objectForKey:CSR_STORE_FlAG] forKey:@"withPerson"];
    }
    
    [params setObject:CSR_STORE_FlAG forKey:@"whichControl"];
    XDPersonChooseViewController *vc = [[XDPersonChooseViewController alloc]initWithParams:params];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidAppear:(BOOL)animated
{
    if (pushflag==1) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        NSMutableArray *choosedPerson = [ud objectForKey:SJR_STORE_FlAG];
        NSMutableString *names = [[NSMutableString alloc]initWithString:@""];
        sjrguids = [[NSMutableString alloc]initWithString:@""];
        for (int i=0; i<choosedPerson.count; i++) {
            NSMutableDictionary *dic = [choosedPerson objectAtIndex:i];
            [names appendString:[dic objectForKey:@"displayname"]];
            [names appendString:@";"];
            
            [sjrguids appendString:[dic objectForKey:@"userguid"]];
            [sjrguids appendString:@";"];
        }
        self.lbsjr.text = names;
        [names release];
        NSLog(@"%@",sjrguids);
    }
    else if(pushflag==2)
    {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        NSMutableArray *choosedPerson = [ud objectForKey:CSR_STORE_FlAG];
        NSMutableString *names = [[NSMutableString alloc]initWithString:@""];
        csrguids = [[NSMutableString alloc]initWithString:@""];
        for (int i=0; i<choosedPerson.count; i++) {
            NSMutableDictionary *dic = [choosedPerson objectAtIndex:i];
            [names appendString:[dic objectForKey:@"displayname"]];
            [names appendString:@";"];
            
            [csrguids appendString:[dic objectForKey:@"userguid"]];
            [csrguids appendString:@";"];
        }
        self.lbcsr.text = names;
        [names release];
        NSLog(@"%@",csrguids);
    }
   
}

- (void)dealloc {
    [_sv release];
    [_lbsjr release];
    [_lbcsr release];
    [_tvContent release];
    [_lbMailTitle release];
    [_tv release];
    [cbMsg release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setSv:nil];
    [self setLbsjr:nil];
    [self setLbcsr:nil];
    [self setTvContent:nil];
    [self setLbMailTitle:nil];
    [self setTv:nil];
    [cbMsg release];
    cbMsg = nil;
    [super viewDidUnload];
}

-(void)refreshUIWithThreadGuid:(NSString *)threadGuid andData:(NSObject *)obj
{
    [self hideMBPHUD];
    
    if ([sendMailTaskGuid isEqualToString:threadGuid]) {
        if ([self validateXML:(NSString *)obj]) {
            [UITool toast:[@"邮件发送成功" retain]];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(void)epointAttachSelected:(NSDictionary *)fileDic
{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
    
    if ([attachArray containsObject:fileDic]) {
        return;
    }
    [attachArray addObject:fileDic];
    [self.tv reloadData];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellItem = @"CellItem";
    XDMailSendAttachListCell *cell = (XDMailSendAttachListCell *)[tableView dequeueReusableCellWithIdentifier:CellItem];
    if (cell==nil) {
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"XDMailSendAttachListCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    NSMutableDictionary *m = [attachArray objectAtIndex:indexPath.row];
    NSString *filename = [m objectForKey:@"filename"];
    if ([filename hasSuffix:@".doc"]||[filename hasSuffix:@".docx"]) {
        cell.ivIcon.image = [UIImage imageNamed:@"img_attach_doc"];
    }
    else if([filename hasSuffix:@"xls"]||[filename hasSuffix:@".xlsx"])
    {
        cell.ivIcon.image = [UIImage imageNamed:@"img_attach_excel"];
    }
    else if([filename hasSuffix:@"pdf"])
    {
        cell.ivIcon.image = [UIImage imageNamed:@"img_pdf_48"];
    }
    else if([filename hasSuffix:@"txt"])
    {
        cell.ivIcon.image = [UIImage imageNamed:@"img_txt_48"];
    }
    else if([filename hasSuffix:@"jpg"])
    {
        cell.ivIcon.image = [UIImage imageNamed:@"img_jpg_48"];
    }
    cell.lbFilename.text = [m objectForKey:@"filename"];
    
    cell.btDelete.tag = indexPath.row;
    [cell.btDelete addTarget:self action:@selector(deleteSingleFile:) forControlEvents:UIControlEventTouchUpInside];
    cell.uvDescription.layer.cornerRadius = 4;
    
    
    
    if ([[m objectForKey:@"type"]isEqualToString:@"2"]) {
        [cell.uvDescription setBackgroundColor:[UIColor blueColor]];
        cell.lbDescription.text = @"转发";
    }
    else
    {
        long filesize =  [[[NSFileManager defaultManager] attributesOfItemAtPath:[m objectForKey:@"filepath"] error:nil] fileSize];
        cell.lbDescription.text = [NSString stringWithFormat:@"%ldk",filesize/1024];
    }
    
    return cell;
}

-(void)deleteSingleFile:(UIButton *)btn
{
    NSLog(@"%i",btn.tag);
    [attachArray removeObjectAtIndex:btn.tag];
    [self.tv reloadData];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return attachArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tv editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	return UITableViewCellEditingStyleDelete;
    
}

//点击删除按钮后, 会触发如下事件. 在该事件中做响应动作就可以了
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle  forRowAtIndexPath:(NSIndexPath *)indexPath {
    [attachArray removeObjectAtIndex:indexPath.row];
    [self.tv reloadData];
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

@end
